import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Layout from '../components/Layout.vue'
import Home from '../views/Home.vue'
import Users from '../views/Users.vue'
import Roles from '../views/Roles.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Home',
        component: Home
      },
      {
        path: 'users',
        name: 'Users',
        component: Users,
        meta: { title: '用户管理' }
      },
      {
        path: 'roles',
        name: 'Roles',
        component: Roles,
        meta: { title: '角色管理' }
      },
      {
        path: '/goods',
        name: 'Goods',
        component: () => import('@/views/GoodsList.vue'),
        meta: { title: '商品管理' }
      },
      {
        path: '/orders',
        component: () => import('@/views/OrderList.vue'),
        meta: { title: '订单管理', icon: 'el-icon-s-order' }
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('token');
    console.log(isLoggedIn);
  if (to.path === '/login') {
    if (isLoggedIn) {
      // 已登录状态下访问登录页，重定向到首页
      next('/');
    } else {
      next();
    }
  } else {
    if (!isLoggedIn) {
      // 未登录状态下访问其他页面，重定向到登录页
      next({ path: '/login', query: { redirect: to.fullPath } });
    } else {
      next();
    }
  }
});

export default router